<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog"
          >添加</el-button
        >
      </div>
    </template>
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="address" label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 60px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-button
            type="warning"
            title="修改"
            :icon="Edit"
            size="small"
            @click="editTrademark(row)"
          />
          <el-button
            type="danger"
            title="删除"
            :icon="Delete"
            size="small"
            @click="removeTrademark(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, jumper,->,sizes,total, "
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademark.id ? '修改' : '添加'}品牌`"
    >
      <el-form :model="trademark" :rules="rules" ref="ruleFormRef">
        <el-form-item label=" 品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label=" 品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件,且不超过50kb</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="btnTrademark">确定</el-button> -->
          <el-button type="primary" @click="submitFrom(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
import type {
  TrademarkListModel,
  TrademarkModel,
} from "@/api/product/model/trademarkModel";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  reqDeleteTrademarkInfo,
  reqGetTrademarkListData,
  reqSaveTrademarkInfo,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark";
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormInstance, FormRules } from "element-plus";

// 上传成功后的图片链接地址
// const imageUrl = ref("");
// 动态读取环境变量中的值
// console.log('ii',import.meta.env);
const BASE_URL = import.meta.env.VITE_API_URL;

// 定义一些数据
const currentPage = ref<number>(1); // 当前页码
const pageSize = ref<number>(3); // 每页要显示的数量
const total = ref<number>(0); // 品牌总数量
const trademarkList = ref<TrademarkListModel>([]);

// 分页器相关的变量
const small = ref<boolean>(false);
const background = ref<boolean>(false);
const disabled = ref<boolean>(false);

// 弹出框
const dialogFormVisible = ref<boolean>(false);
const formLabelWidth = "140px";

// 数据校验
const ruleFormRef = ref<FormInstance>();
// 11. 数据校验
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请添加品牌名称", trigger: "blur" },
    { min: 1, max: 6, message: "长度在1-6之间", trigger: "blur" },
  ],
  logoUrl: [
    { required: true, message: "请选择要上传的图片", trigger: "change" },
  ],
});

// 每次调用这个函数都会返回一个新的独立对象，和之前的数据没有关系
const initTrademark = () => ({ tmName: "", logoUrl: "" });
// 品牌上传需要用到的响应式对象
const trademark = reactive<TrademarkModel>(initTrademark());

const loading = ref<boolean>(true);
// 定义一个方法来获取数据
// 1. 根据分页获取品牌数据
const getTrademarkListData = async () => {
  loading.value = true;
  // const result = await reqGetTrademarkListData(1, 5);
  const result = await reqGetTrademarkListData(
    currentPage.value,
    pageSize.value
  );
  // console.log('trademark',result);
  trademarkList.value = result.records;
  total.value = result.total;

  loading.value = false;
};
// 2. 组件挂载完成时的逻辑
onMounted(() => {
  // 发送请求
  getTrademarkListData();
});

//  分页器相关的两个事件
// 3. 更改每页显示器条数时触发的事件处理程序
const handleSizeChange = (val: number) => {
  // val === pageSize
  pageSize.value = val;
  currentPage.value = 1; // 把当前页码再重置为1
  // 重新发送请求,获取数据
  getTrademarkListData();
};
// 4. 根据当前页面进行切换时触发的函数
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  // 重新发送请求,获取新页码中的数据
  getTrademarkListData();
};

// 图片上传时的两个函数
// 5. 图片上传成功后执行的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // form.logoUrl = response.data;
  trademark.logoUrl = response.data;

  // 清除校验规则
  ruleFormRef.value?.clearValidate(["logoUrl"]);
};

// 6. 图片上传前校验的函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgTypes = ["image/jpeg", "image/jpg", "image/png"];
  // if (rawFile.type !== "image/jpeg") {
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片的格式只能是jpg/png/jpeg,请重新选择");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M,请重新选择...!");
    return false;
  }
  return true;
};

// 7. 实现添加品牌
// 修改校验规则
const submitFrom = async (formEl: FormInstance | undefined) => {
  let result;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (trademark.id) {
        reqUpdateTrademarkInfo(trademark);
      } else {
        reqSaveTrademarkInfo(trademark);
      }
      // 要提示添加成功
      ElMessage({
        message: "操作品牌成功...",
        type: "success",
      });
      // 关闭对话框
      dialogFormVisible.value = false;
      // 跳转到第一页
      // currentPage.value = 1;
      !trademark.id ? (currentPage.value = 1) : currentPage.value;
      // 重新发送请求
      getTrademarkListData();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 8. 当在此点击'添加品牌'按钮时，弹出对话框，清空之前的数据
const showTrademarkDialog = () => {
  Object.assign(trademark, initTrademark());
  delete trademark.id; // 清除一下id
  dialogFormVisible.value = true;

  // 清除校验规则
  ruleFormRef.value?.clearValidate();
};

// 9. 单击删除按钮，弹出提示框
const removeTrademark = (row: TrademarkModel) => {
  // ElMessageBox.confirm(
  //   '你真的要删除这条数据吗?',
  //   '提示',
  //   {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning',
  //   }
  // )
  ElMessageBox.confirm(`你真的要删除${row.tmName}这条数据吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademarkInfo(row.id as number);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      // 如果删除的是最好一页的最后一条数据，则需要让当前页码减一
      currentPage.value =
        trademarkList.value.length > 1
          ? currentPage.value
          : currentPage.value - 1;
      // 重新渲染页面
      getTrademarkListData();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 10. 修改品牌
const editTrademark = (row: TrademarkModel) => {
  // 将需要显示出来的品牌数据给trademark进行赋值，因为数据是响应式的，页面会渲染出来
  Object.assign(trademark, row); // row里面是有id的
  dialogFormVisible.value = true;

  // 清除校验规则
  ruleFormRef.value?.clearValidate();
};
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

/* .box-card {
  width: 480px;
} */
.el-input {
  width: 78%;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>